﻿import json

from Devices.Chiot.ChiotDeviceParser import ChiotDeviceParser
from Devices.Chiot.Bulb.DeviceBulb import DeviceBulb

class BulbParser(ChiotDeviceParser):
    def PackSetSwitch(on):
        msgvalue = {}
        ChiotDeviceParser.PackAttr(msgvalue, "switch", "on",1 if on else 0)

        obj = {}
        jsonDoc = ChiotDeviceParser.PackBase(obj, msgvalue, "setAttributes")
        return json.dumps(jsonDoc, separators=(',', ':'))

    def PackSetNoDisturb(on):
        msgvalue = {}
        ChiotDeviceParser.PackAttr(msgvalue, "noDisturb", "on",1 if on else 0)

        obj = {}
        jsonDoc = ChiotDeviceParser.PackBase(obj, msgvalue, "setAttributes")
        return json.dumps(jsonDoc, separators=(',', ':'))

    def PackSetRGB(rgb):
        msgvalue = {}
        ChiotDeviceParser.PackAttr(msgvalue, "lightMode", "status", int(DeviceBulb.LightMode.LIGHT_RGB))
        ChiotDeviceParser.PackAttr(msgvalue, "rgbBrightness", "brightness", rgb.rgbBrightness)
        ChiotDeviceParser.PackAttr(msgvalue, "saturation", "ratio", rgb.saturation)
        ChiotDeviceParser.PackAttr(msgvalue, "colour", "red", rgb.red)
        ChiotDeviceParser.PackAttr(msgvalue, "colour", "green", rgb.green)
        ChiotDeviceParser.PackAttr(msgvalue, "colour", "blue", rgb.blue)

        obj = {}
        jsonDoc = ChiotDeviceParser.PackBase(obj, msgvalue, "setAttributes")
        return json.dumps(jsonDoc, separators=(',', ':'))

    def PackSetWhite(white):
        msgvalue = {}
        ChiotDeviceParser.PackAttr(msgvalue, "lightMode", "status", int(DeviceBulb.LightMode.LIGHT_WHITE))
        ChiotDeviceParser.PackAttr(msgvalue, "whiteBrightness", "brightness", white.whiteBrightness)
        ChiotDeviceParser.PackAttr(msgvalue, "colorTemperature", "ratio", white.temprature)

        obj = {}
        jsonDoc = ChiotDeviceParser.PackBase(obj, msgvalue, "setAttributes")
        return json.dumps(jsonDoc, separators=(',', ':'))

    def PackSetAtmosphere(id, script):
        msgvalue = {}
        ChiotDeviceParser.PackAttr(msgvalue, "lightMode", "status", int(DeviceBulb.LightMode.LIGHT_ATMOSPHERE))
        ChiotDeviceParser.PackAttr(msgvalue, "atmosphere", "id", int(id) if id.isdigit() else 0)
        ChiotDeviceParser.PackAttr(msgvalue, "atmosphere", "script", script)

        obj = {}
        jsonDoc = ChiotDeviceParser.PackBase(obj, msgvalue, "setAttributes")
        return json.dumps(jsonDoc, separators=(',', ':'))

    def PackSetAtmosphereSend(id, script):
        msgvalue = {}
        ChiotDeviceParser.PackAttr(msgvalue, "atmosphere", "id", int(id) if id.isdigit() else 0)
        ChiotDeviceParser.PackAttr(msgvalue, "atmosphere", "script", script)

        obj = {}
        jsonDoc = ChiotDeviceParser.PackBase(obj, msgvalue, "setAttributes")
        return json.dumps(jsonDoc, separators=(',', ':'))

    def PackSetLight(attrName, propertyName, value):
        msgvalue = {}
        ChiotDeviceParser.PackAttr(msgvalue, attrName, propertyName, value)

        obj = {}
        jsonDoc = ChiotDeviceParser.PackBase(obj, msgvalue, "setAttributes")
        return json.dumps(jsonDoc, separators=(',', ':'))

    def PackSetMemoryLightMode(mode):
        msgvalue = {}
        ChiotDeviceParser.PackAttr(msgvalue, "memoryLightMode", "status", int(mode))

        obj = {}
        jsonDoc = ChiotDeviceParser.PackBase(obj, msgvalue, "setAttributes")
        return json.dumps(jsonDoc, separators=(',', ':'))

    def PackSetMemoryLightAttr(serviceList):
        services = []
        for i in range(len(serviceList)):
            service = {}
            service["serviceId"] = serviceList[i].serviceId
            service["para"] = serviceList[i].para
            service["paraValue"] = serviceList[i].paraValue
            services.append(service)
        msgvalue = {}
        msgvalue["memoryLight"] = services
        obj = {}
        jsonDoc = ChiotDeviceParser.PackBase(obj, msgvalue, "setMemoryLight")
        return json.dumps(jsonDoc, separators=(',', ':'))

    def PackSetPowerType(powerType):
        obj = {}
        obj["client"] = "TEST"
        obj["cmd"] = "setPowerType"
        obj["powerType"] = int(powerType)

        return json.dumps(obj, separators=(',', ':'))

    def PackSetLedDriver(ledDriver):
        obj = {}
        obj["client"] = "TEST"
        obj["cmd"] = "setLedDriver"
        obj["ledDriver"] = int(ledDriver)

        return json.dumps(obj, separators=(',', ':'))

    def PackSetCloudType(cloudType):
        obj = {}
        obj["client"] = "TEST"
        obj["cmd"] = "setCloudType"
        obj["cloudType"] = int(cloudType)

        return json.dumps(obj, separators=(',', ':'))

    def PackSetInterfaceType(interfaceType):
        obj = {}
        obj["client"] = "TEST"
        obj["cmd"] = "setInterfaceType"
        obj["interfaceType"] = int(interfaceType)

        return json.dumps(obj, separators=(',', ':'))

    def PackSetGradientTime(time):
        obj = {}
        obj["client"] = "TEST"
        obj["cmd"] = "setGradientTime"
        obj["gradientTime"] = int(time)

        return json.dumps(obj, separators=(',', ':'))   

    def PackSetWiFi(ssid, pwd):
        obj = {}
        obj["client"] = "TEST"
        obj["cmd"] = "setWiFi"
        obj["ssid"] = ssid
        obj["pwd"] = pwd

        return json.dumps(obj, separators=(',', ':'))

    def PackSetScheduleOpenLog(enable):
        obj = {}
        obj["client"] = "TEST"
        obj["cmd"] = "setSchedule"
        obj["openLog"] = int(enable)

        return json.dumps(obj, separators=(',', ':'))

    def PackSetCurrent(current_red, current_green, current_blue, current_w, current_c):
        obj = {}
        obj["client"] = "TEST"
        obj["cmd"] = "setCurrent"
        obj["red"] = current_red
        obj["green"] = current_green
        obj["blue"] = current_blue
        obj["cold"] = current_c
        obj["warm"] = current_w

        return json.dumps(obj, separators=(',', ':'))

    def SetLightAttr(lightAttr, serviceList):
        for i in range(len(serviceList)):
            if "lightMode" == serviceList[i].serviceId:
                lightAttr.lightMode = serviceList[i].paraValue
            elif "colour" == serviceList[i].serviceId:
                if "red" == serviceList[i].para:
                    lightAttr.rgb.red = serviceList[i].paraValue
                elif "green" == serviceList[i].para:
                    lightAttr.rgb.green = serviceList[i].paraValue
                elif "blue" == serviceList[i].para:
                    lightAttr.rgb.blue = serviceList[i].paraValue
            elif "rgbBrightness" == serviceList[i].serviceId:
                lightAttr.rgb.rgbBrightness = serviceList[i].paraValue
            elif "saturation" == serviceList[i].serviceId:
                lightAttr.rgb.saturation = serviceList[i].paraValue
            elif "whiteBrightness" == serviceList[i].serviceId:
                lightAttr.white.whiteBrightness = serviceList[i].paraValue
            elif "colorTemperature" == serviceList[i].serviceId:
                lightAttr.white.temprature = BulbParser.TemperatureRate(serviceList[i].paraValue)
            else:
                print("Unknown serviceId " << serviceList[i].serviceId)

    def GetCurrents(obj, attrName, currents):
        if not attrName in obj:
            return False

        currents_obj = obj[attrName]
        currents.red = int(currents_obj["red"])
        currents.green = int(currents_obj["green"])
        currents.blue = int(currents_obj["blue"])
        currents.warm = int(currents_obj["warm"])
        currents.cold = int(currents_obj["cold"])

        return True
    
    #开尔文温度转换为温度比例
    def TemperatureRate(value):
        MAX_COLOR_TEMP = 6500
        MIN_COLOR_TEMP = 2700

        #是温度比例则直接返回
        if value <= 100:
            return value

        if value > MAX_COLOR_TEMP:
            value = MAX_COLOR_TEMP

        if value < MIN_COLOR_TEMP:
            value = MIN_COLOR_TEMP

        rate = (MAX_COLOR_TEMP - value) / (MAX_COLOR_TEMP - MIN_COLOR_TEMP) * 100.0
        return int(rate)

    def ParseFullStatus(msgValue, fullStatus):
        ret, strValue = ChiotDeviceParser.GetStrProperty(msgValue, "mac")
        if ret:
            fullStatus.mac = strValue

        ret, value = ChiotDeviceParser.GetIntProperty(msgValue, "heartbeatFreq")
        if ret:
            fullStatus.heartbeatFreq = value

        ret, strValue = ChiotDeviceParser.GetStrProperty(msgValue, "firmwareVersion")
        if ret:
            fullStatus.firmwareVersion = strValue

        ret, strValue = ChiotDeviceParser.GetStrProperty(msgValue, "hardwareVersion")
        if ret:
            fullStatus.hardwareVersion = strValue

        ret, strValue = ChiotDeviceParser.GetStrProperty(msgValue, "modelId")
        if ret:
            fullStatus.modelId = strValue
            
        ret, strValue = ChiotDeviceParser.GetStrProperty(msgValue, "protocol")
        if ret:
            fullStatus.protocol = strValue

        ret, strValue = ChiotDeviceParser.GetStrProperty(msgValue, "build_time")
        if ret:
            fullStatus.buildTime = strValue

        ret, value = ChiotDeviceParser.GetIntProperty(msgValue, "power_type")
        if ret:
            fullStatus.powerType = value

        ret, value = ChiotDeviceParser.GetIntProperty(msgValue, "led_driver")
        if ret:
            fullStatus.ledDriver = value

        ret, value = ChiotDeviceParser.GetIntProperty(msgValue, "cloud_type")
        if ret:
            fullStatus.cloudType = value

        ret, value = ChiotDeviceParser.GetIntProperty(msgValue, "interface_type")
        if ret:
            fullStatus.interfaceType = value
            
        ret, value = ChiotDeviceParser.GetIntProperty(msgValue, "gradient_time")
        if ret:
            fullStatus.gradientTime = value

        ret, value = ChiotDeviceParser.GetIntProperty(msgValue, "schedule_open_log")
        if ret:
            fullStatus.scheduleOpenLog = bool(value)

        BulbParser.GetCurrents(msgValue, "currents", fullStatus.currents)

        if not "stateValue" in msgValue:
            return True
        stateValue = msgValue["stateValue"]

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "switch", "on")
        if ret:
            fullStatus.switch_state = value

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "noDisturb", "on")
        if ret:
            fullStatus.noDisturb = value

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "lightMode", "status")
        if ret:
            fullStatus.lightAttr.lightMode = value

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "rgbBrightness", "brightness")
        if ret:
            fullStatus.lightAttr.rgb.rgbBrightness = value

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "whiteBrightness", "brightness")
        if ret:
            fullStatus.lightAttr.white.whiteBrightness = value

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "saturation", "ratio")
        if ret:
            fullStatus.lightAttr.rgb.saturation = value

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "colour", "red")
        if ret:
            fullStatus.lightAttr.rgb.red = value

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "colour", "green")
        if ret:
            fullStatus.lightAttr.rgb.green = value

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "colour", "blue")
        if ret:
            fullStatus.lightAttr.rgb.blue = value

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "colorTemperature", "ratio")
        if ret:
            fullStatus.lightAttr.white.temprature = BulbParser.TemperatureRate(value)
        else:
            ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "colorTemperature", "value")
            if ret:
                fullStatus.lightAttr.white.temprature = BulbParser.TemperatureRate(value)

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "memoryLightMode", "status")
        if ret:
            fullStatus.memoryLightMode = value

        ret, serviceList = ChiotDeviceParser.GetServices(stateValue, "memoryLight")
        if ret:
            BulbParser.SetLightAttr(fullStatus.memoryLightAttr, serviceList)

        ret, value = ChiotDeviceParser.GetIntProperty(stateValue, "atmosphere", "id")
        if ret:
            fullStatus.atmosphereAttr.id = value

        ret, strValue = ChiotDeviceParser.GetStrProperty(stateValue, "atmosphere", "script")
        if ret:
            fullStatus.atmosphereAttr.script = strValue

        BulbParser.GetTimers(stateValue, "timer", fullStatus.timers)
        BulbParser.GetDelay(stateValue, "delay", fullStatus.delay)

        ret, strValue = ChiotDeviceParser.GetStrProperty(stateValue, "timezone", "timezone")
        if ret:
            fullStatus.timezone = strValue

        return True

